﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Input;
using FFImageLoading.Forms;
using mb;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Shared
{
    public class BasePage : ContentPage
    {
        protected static ILog logger = App.logger;

        protected bool LoadXamlFromRes(string name)
        {
            string path = $"{App.HotStorageRoot}/res/xforms/{name}.xaml";
            try
            {
                string pn = DeviceInfo.Platform == DevicePlatform.iOS? "iOS": "DroidLib";
                string xaml = File.ReadAllText(path);
                xaml = xaml.Replace("${MainAssembly}", "mb." + pn);
                this.LoadFromXaml(xaml);
                return true;
            }
            catch (Exception e)
            {
                logger.Log("load xaml failed", name, e);
                return false;
            }
        }

    }

    // [XamlCompilation(XamlCompilationOptions.Compile)]
    public class PhonewordPage : BasePage
    {
        string _translatedNumber;
        Button translateButon;
        Button callButton;
        Button callHistoryButton;

        public PhonewordPage()
        {
            if (this.LoadXamlFromRes("me"))
            {
                this.translateButon = this.FindByName("translateButon") as Button;
                this.translateButon.Clicked += (s, e) =>
                {
                    App.logger.Log("click");
                };

                var img = new Image();
                var src = ImageSource.FromFile($"{App.HotStorageRoot}/res/logo.png");
                img.Source = src;
                (this.Content as StackLayout).Children.Add(img);
            }
        }

        void OnTranslate(object sender, EventArgs e)
        {
            //_translatedNumber = PhonewordTranslatorService.ToNumber(phoneNumberText.Text);
            if (!string.IsNullOrWhiteSpace(_translatedNumber))
            {
                callButton.IsEnabled = true;
                callButton.Text = "Call " + _translatedNumber;
            }
            else
            {
                callButton.IsEnabled = false;
                callButton.Text = "Call";
            }
        }

        async void OnCall(object sender, EventArgs e)
        {
            if (await this.DisplayAlert(
                    "Dial a Number",
                    "Would you like to call " + _translatedNumber + "?",
                    "Yes",
                    "No"))
            {
                callHistoryButton.IsEnabled = true;
            }
        }

        void OnCallHistory(object sender, EventArgs e) { }
    }

}